package cn.pn.project.controller;

import cn.pn.project.client.base.ImgFeign;
import cn.pn.project.client.comment.CommentFeign;
import cn.pn.project.client.commodity.CommodityFeign;
import cn.pn.project.client.user.UserFeign;
import cn.pn.project.common.Dto;
import cn.pn.project.common.DtoUtil;
import cn.pn.project.common.Page;
import cn.pn.project.pojo.base.Img;
import cn.pn.project.pojo.comment.Comment;
import cn.pn.project.pojo.comment.Like;
import cn.pn.project.pojo.commodity.Commodity;
import cn.pn.project.pojo.user.User;
import cn.pn.project.utils.BadWordUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api")
public class CommentController {
    @Autowired
    private CommentFeign commentFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private CommodityFeign commodityFeign;
    @Autowired
    private ImgFeign imgFeign;


    /**
     * 根据评论id查询评论信息
     * @param commentId
     * @throws Exception
     */
    @RequestMapping("/p/commentById")
    public Object getCommentByCommentId(@RequestParam("commentId")Integer commentId) throws Exception{
        System.out.println("-----------------/p/commentById：根据评论id查询评论-----------------");
        Map<Object,Object> resultMap=new HashMap();
        //根据根据评论id查询评论对象
        Comment comment=commentFeign.getCommentByCommentId(commentId);
        if(comment!=null){//调用userFeign得到用户信息
            User user=userFeign.findUserById(comment.getUserId());//主评论的user信息
            comment.setUser(user);
            //如果图片id不为0则调用图片feign获取图片对象
            //comment.setImg();
            //查询该评论下的子集合放入主评论
            Page<Comment> commentPage=commentFeign.listChildComment(commentId,comment.getCommodityId(),1,10);
            if(commentPage.getRows().size()>0){//如果该商品有主评论就拿取用户id去查找用户的信息集合
                for (Comment comm:commentPage.getRows()) {//多线程调用用户feign
                    User childUser=userFeign.findUserById(comm.getUserId());
                    comm.setUser(childUser);
                }
            }
            comment.setChildComments(commentPage);
            //调用商品feign查询商品信息
            comment.setCommodity(commodityFeign.getCommodityByCommodityId(comment.getCommodityId()));
        }
        resultMap.put("comment",comment);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 查询所有主评论
     * @param commodityId 商品id
     * @param pageNo 当前页数
     * @param pageSize 页面容量
     * @return
     */
    @RequestMapping(value = "/p/listMain")
    public Object listMainComment(@RequestParam("commodityId") Integer commodityId,@RequestParam(value="pageNo",defaultValue = "1") Integer pageNo,@RequestParam(value="pageSize",defaultValue = "10") Integer pageSize){
        System.out.println("-----------consumer的/comment/listMain方法-----------");
        System.out.println("commodityId:"+commodityId+",pageNo:"+pageNo+",pageSize:"+pageSize);
        Page<Comment> page=commentFeign.listMainComment(commodityId,pageNo,pageSize);
        if(page.getRows().size()>0){//如果该商品有主评论就拿取用户id去查找用户的信息集合
            //多线程调用用户feign
            for (Comment comm:page.getRows()) {
                User user=userFeign.findUserById(comm.getUserId());
                comm.setUser(user);
                /*if(comm.getImgId()>0){

                }*/
            }
        }
        //多线程调用商品feign获取信息
        Commodity commodity= commodityFeign.getCommodityByCommodityId(commodityId);
        //返回总集合
        Map<String,Object> resultMap=new HashMap<String,Object>();
        //主评论分页
        resultMap.put("page",page);
        //商品信息
        resultMap.put("commodity",commodity);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 查询某商品主评论数量
     * @param commodityId
     * @return
     */
    @RequestMapping("/p/mainCommentCount")
    public Object allCommentNum(@RequestParam("commodityId") Integer commodityId){
        System.out.println("-------------------查询商品主评论数量-------------------");
        return commentFeign.mainCommentCount(commodityId);
    }

    /**
     * 查询某一主评论的所有子评论
     * @param belongToId 所属主评论id
     * @param commodityId 商品id
     * @param pageNo 当前页数
     * @param pageSize 页面容量
     * @return
     * @throws Exception
     */
    @RequestMapping("/p/listChild")
    public String listChildComment(@RequestParam("belongToId") Integer belongToId
            ,@RequestParam("commodityId")Integer commodityId
            ,@RequestParam(value="pageNo",defaultValue = "1") Integer pageNo
            ,@RequestParam(value="pageSize",defaultValue = "10") Integer pageSize) throws Exception {
        //多线程调用用户feign
        System.out.println("-----------consumer的/comment/listChild方法-----------");
        Page<Comment> commentPage=commentFeign.listChildComment(belongToId,commodityId,pageNo,pageSize);
        if(commentPage.getRows().size()>0){//如果该商品有主评论就拿取用户id去查找用户的信息集合
            for (Comment comm:commentPage.getRows()) {//多线程调用用户feign
                User user=userFeign.findUserById(comm.getUserId());
                comm.setUser(user);
            }
        }
        return JSON.toJSONString(commentPage,true);
    }


    /**
     * 查找某用户对某商品有无评论
     * @param userId 用户id
     * @param commodityId 商品id
     * @return 评论对象
     * @throws Exception
     */
    @RequestMapping(value = "/p/findMain",method = RequestMethod.POST)
    public String isCommentOn(@RequestParam("userId")Integer userId,@RequestParam("commodityId")Integer commodityId) throws Exception {
        //多线程调用用户feign
        //多线程调用商品feign
        //查找出来所有的主评论，在绑定数据时根据用户id匹配集合中的用户id
        //如果绑定后未找到该用户对这个商品的评论，显示我要评论，若点击则为添加
        //如果找到了则显示我的评论，若点击则获取该评论
        return JSON.toJSONString(commentFeign.isCommentedOn(userId,commodityId));
    }

    /**
     * 添加主评论/子评论
     * @param comment 评论
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/add")
    public Dto addComment(Comment comment) throws Exception{
        System.out.println(comment.getContent());
        //将敏感词替换为* 过滤敏感词
        comment.setContent(BadWordUtil.replaceBadWord(comment.getContent(),1,"*"));
        System.out.println("修改后的评论："+comment.getContent()+"图片id："+comment.getImgId()+"fatherId："+comment.getFatherId());
        comment.setCommentTime(new Date());
        if(comment.getFatherId()==0){//添加主评论
            Comment commentBack=commentFeign.addMainComment(comment);//先添加一条主评论
            if(commentBack.getImgId()>0){//判断是否有上传图片操作
                System.out.println("》》》》》》》》》》》》》》》评论id："+commentFeign.getMaxId());
                //更新图片表的关联id
                Integer commUpResult=imgFeign.updateReleId(commentFeign.getMaxId(),commentBack.getImgId());
                if(commentBack!=null&&commUpResult>0){
                    return DtoUtil.returnDataSuccess(commentBack);
                }else {
                    return DtoUtil.returnFail("新增主评论失败","6002");
                }
            }else{
                if(commentBack!=null){
                    return DtoUtil.returnDataSuccess(commentBack);
                }else {
                    return DtoUtil.returnFail("新增主评论失败","6002");
                }
            }
        }else{//添加子评论
            comment.setLevel(0);//评论星级
            comment.setImgId(0);//图片id
            Integer result=commentFeign.addChildComment(comment);
            if(result>0){
                return DtoUtil.returnSuccess();
            }else {
                return DtoUtil.returnFail("添加子评论失败", "6002");
            }
        }

    }
    /**
     * 多图上传
     * @param files
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/p/fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws Exception {
        String imgPath="";
        if(files!=null && files.length>0){//有图
            System.out.println(">>>>>>>>>>>>>>有图-图片个数："+files.length+">>>>>>>>>>>>>>");
            for(int i=0;i<files.length;i++){
                MultipartFile file=files[i];
                //保存图片
                imgPath+=this.saveFile(request,file)+(i<files.length-1?"*":"");
            }
            System.out.println(">>>>>>>>>>>>>>>>>保存到数据库的图片路径："+imgPath+">>>>>>>>>>>>>>>>>");
            //将图片保存到数据库中
            Img img=new Img();
            img.setImgURL(imgPath);//设置图片路径
            img.setReleId(0);//设置关联id为0，等评论数据提交后修改图片关联id
            Integer result=imgFeign.addImg(img);//新增图片记录 将返回的图片id返回给ajax
            img.setImgId(imgFeign.getMaxId());
            System.out.println(">>>>>>>>>>>>>>>>>>>>.图片id："+img.getImgId());
            if(result>0){
                System.out.println("图片新增成功");
                System.out.println(JSON.toJSONString(img.getImgId()));
                return JSON.toJSONString(img.getImgId());
            }else{
                System.out.println("图片新增失败");
                return JSON.toJSONString("imgId",0);
            }
        }else{
            System.out.println(">>>>>>>>>>>>>>进无图片-图片个数："+files.length+">>>>>>>>>>>>>>");
            return JSON.toJSONString("exception");
        }
    }


    private String saveFile(HttpServletRequest request,MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String name = file.getName();
        String randomUUID = UUID.randomUUID().toString();
        int index = originalFilename.lastIndexOf(".");
        String exet = originalFilename.substring(index);
        Date date = new Date();
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd\\HH\\mm\\ss");
        //String dateStr = sdf.format(date); // D:\\uploads\\20180824 String
        String filePath = "D:\\pn\\comment\\img\\";
        System.out.println("filePath=" + filePath);
        File file2 = new File(filePath);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        //经过转换后的图片名称
        String imgPath=randomUUID+exet;
        System.out.println("图片名="+imgPath);
        filePath += "\\" + randomUUID + exet;
        System.out.println(filePath);
        file.transferTo(new File(filePath));// ctrl+1
        return imgPath;
    }





    /**
     * 修改主评论
     * @param comment
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/v/update")
    public Dto<Comment> updateComment(Comment comment) throws Exception{
        //将敏感词替换为*
        comment.setContent(BadWordUtil.replaceBadWord(comment.getContent(),1,"*"));
        Comment commentBack=commentFeign.updateComment(comment);
        if(commentBack!=null){
            return DtoUtil.returnDataSuccess(commentBack);
        }else {
            return DtoUtil.returnFail("获取数据失败","6002");
        }
    }

    /**
     * 点赞
     * @param like
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/v/like")
    public Dto isLikedOn(Like like) throws Exception{
        //限制频繁操作

        int result=commentFeign.isLikedOn(like);
        if(result>0){//查到记录则取消点赞
            int jie1=commentFeign.delLike(like);
            if(jie1>0){
                return DtoUtil.returnSuccess();
            }else{
                return DtoUtil.returnFail("操作失败", "6002");
            }
        } else{//未查到记录则点赞
            int jie1=commentFeign.addLike(like);
            if(jie1>0){
                return DtoUtil.returnSuccess();
            }else{
                return DtoUtil.returnFail("操作失败", "6002");
            }
        }
    }


}
